<?php

/**

 * 同城微聚汇

 * ============================================================================

 * 版权所有 2015-2027 武汉鼎联信息技术有限公司，并保留所有权利。

 * 网站地址: http://dlshop.dliansoft.com

 * ----------------------------------------------------------------------------

 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .

 * 不允许对程序代码以任何形式任何目的的再发布。

 * ============================================================================

 * Author: IT宇宙人

 * Date: 2015-09-09

 * 参考地址 http://www.cnblogs.com/txw1958/p/weixin-js-sharetimeline.html

 * http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html  微信JS-SDK说明文档

 */

namespace app\mobile\logic;

use think\Model;

/**

 * 分类逻辑定义

 * Class CatsLogic

 * @package Home\Logic

 */

class Jssdk extends Model

{

 

  private $appId;

  private $appSecret;



  public function __construct($appId, $appSecret) {

    $this->appId = $appId;

    $this->appSecret = $appSecret;

  }

  // 签名

  public function getSignPackage() {

    $jsapiTicket = $this->getJsApiTicket();



    // 注意 URL 一定要动态获取，不能 hardcode.

    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";



    $timestamp = time();

    $nonceStr = $this->createNonceStr();



    // 这里参数的顺序要按照 key 值 ASCII 码升序排序

    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";



    $signature = sha1($string);



    $signPackage = array(

      "appId"     => $this->appId,

      "nonceStr"  => $nonceStr,

      "timestamp" => $timestamp,

      "url"       => $url,

      "rawString" => $string,

      "signature" => $signature

      

    );

    return $signPackage; 

  }

// 随机字符串

  private function createNonceStr($length = 16) {

    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    $str = "";

    for ($i = 0; $i < $length; $i++) {

      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);

    }

    return $str;

  }





    /**

     * 根据 access_token 获取 icket

     * @return type

     */

    public function getJsApiTicket(){        

        

        $ticket = S('ticket');

        if(!empty($ticket))

            return $ticket;

        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";

        $return = httpRequest($url,'GET');

        $return = json_decode($return,1);        

        S('ticket',$return['ticket'],7000);

        return $return['ticket'];

    }     

      

  

    /**

     * 获取 网页授权登录access token

     * @return type

     */

    public function getAccessToken(){

        //判断是否过了缓存期

        $access_token = S('access_token');

        if(!empty($access_token))

            return $access_token;

        

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";

        $return = httpRequest($url,'GET');

        $return = json_decode($return,1);

        S('access_token',$return['access_token'],7000);        

        return $return['access_token'];

    }   

    /**

     * 根据 access_token 获取 api_ticket

     * @return type

     */

    public function getapiTicket(){        

        
        $ticket = S('api_ticket');

        if(!empty($ticket))

            return $ticket;

        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=wx_card";

        $return = httpRequest($url,'GET');

        $return = json_decode($return,1);        

        S('api_ticket',$return['ticket'],7000);

        return $return['ticket'];

    }   

    public function getCardSign($openid,$timestamp,$nonce_str,$card_id){
        $api_ticket=$this->getapiTicket();
        $card = array(
                    $timestamp,
                    $api_ticket,
                    $card_id,
                    $nonce_str
                );
        $result['timestamp'] =$timestamp;
        $result['card_id'] =$card_id;
        $result['api_ticket'] =$api_ticket;
        $result['nonce_str'] =$nonce_str;
        sort($card,SORT_STRING);
        $result['pai']=implode($card);
        $result['sign'] = sha1(implode($card));
        //var_dump($result);

        if (!$result['sign'])
            return false;
        return $result;
    }


    // 获取一般的 access_token

    public function get_access_token(){

        //判断是否过了缓存期

        $wechat = M('wx_user')->where(array('appid'=>$this->appId))->find();
        $expire_time = $wechat['web_expires'];

        if($expire_time > time()){

           return $wechat['web_access_token'];

        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wechat['appid']}&secret={$wechat['appsecret']}";

        $return = httpRequest($url,'GET');

        $return = json_decode($return,1);

        $web_expires = time() + 7000; // 提前200秒过期

        M('wx_user')->where(array('id'=>$wechat['id']))->save(array('web_access_token'=>$return['access_token'],'web_expires'=>$web_expires));

        return $return['access_token'];

    }   

    

    /*

     * 向用户推送消息

     */

    public function push_msg($openid,$content,$type='text'){

        $access_token = $this->get_access_token();

        $url ="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}"; 
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";       
        if($type=="text"){
          $post_arr = array(

                          'touser'=>$openid,

                          'msgtype'=>$type,

                          'text'=>array(
                                'content'=>$content,
                            )
                          );
        }
        if($type=="news"){
          $post_arr = array (
              'touser' => $openid,
              'msgtype' => 'news',
              'news' => 
              array (
                'articles' => 
                array (
                  0 => 
                  array (
                    'title' => $content['title'],
                    'description' => $content['description'],
                    'url' => $content['url'],
                    'picurl' =>$content['picurl'],
                  ),
                ),
              ),
            );
        }
        

        $post_str = json_encode($post_arr,JSON_UNESCAPED_UNICODE);        

        $return = httpRequest($url,'POST',$post_str);

        $return = json_decode($return,true);        

    }

    /*

     * 向用户推送模板消息

     */

    public function push_tplmsg($openid,$content,$href,$temp_msg){

        $access_token = $this->get_access_token();
        if($temp_msg=='recharge'||$temp_msg=='distribut_recharge'){
          $template_id='CTCrqM4m9MtbyntYbbD1P3MJTP82cfzYtwSKEiu1hYM';
        }
         if($temp_msg=='order'||$temp_msg=='order_action'||$temp_msg=='give_points'||$temp_msg=='consume_points'){
          $template_id='HdRrj_n1K6gcIZ5QWf1t70Wivoc_R9NzKuj2lRnX97M';
        }
        if($temp_msg=='reg'){
          $template_id='SJrTKKIpPbYK2RZCq1sU9krXLm4PmiWL8vmZHiA8ylI';
        }
        if($temp_msg=='distribut'){
          $template_id='8jqkwKdS0IEZaupAYg1MrobQovUfIZfmzC6ad_qnbR4';
        }
        if($temp_msg=='recharge_give'){
          $template_id='JP8eLXFx2765CNf2vJ_0qkF4NdrmEWYbcIMqEEgyB2E';
        }
         if($temp_msg=='admin'){
          $template_id='snOp_1h12uU2ylj0zAb10DGC42UuxjwsrGoKyFAXi8Y';
        }
        

        $url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";  
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; 
        $post_arr = array (
          'touser' => $openid,
          'template_id' => $template_id,
          'url' =>  $protocol.$_SERVER[HTTP_HOST].$href,
          'topcolor' => '#FF0000',
          'data' => $content
        );   

        $post_str = json_encode($post_arr,JSON_UNESCAPED_UNICODE);        

        $return = httpRequest($url,'POST',$post_str);
       // echo'<script>alert('.$return.')</script>';
        $return = json_decode($return,true);
        return $return;

    }

 

}